package w.z.x.framework.repository.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * 主数据源
 *
 * @author 魏祖潇
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "spring.datasource.master")
public class MasterDataSource implements Ordered {
    private String type;
    private String driverClassName;

    private String url;

    private String username;

    private String password;

    private Integer initialSize;

    private Integer minIdle;

    private Integer maxActive;

    private String validationQuery;

    private Long maxWait;

    private String filters;

    @ConditionalOnProperty("spring.datasource.master.url")
    @Bean(name = "dataSource")
    public DataSource master() {
        log.info("!! master => {}", this);
        DruidDataSource dds = new DruidDataSource();
        dds.setName("master");
        dds.setDriverClassName(driverClassName);
        dds.setUrl(url);
        dds.setUsername(username);
        dds.setPassword(password);
        dds.setInitialSize(Objects.isNull(initialSize) ? 5 :initialSize);
        dds.setMinIdle(Objects.isNull(minIdle) ? 5 :minIdle);
        dds.setMaxActive(Objects.isNull(maxActive) ? 100 :maxActive);
        dds.setValidationQuery(Objects.isNull(validationQuery) ? "select 1" : validationQuery);
        dds.setMaxWait(Objects.isNull(maxWait) ? 30000L : maxWait);
        return dds;
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
